package kr.co.coffee247soft.request;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.Certificate;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


public class Request247soft
{
//	private String preUrl = "http://locathost:8080/coffee247soft";
	private String preUrl = "http://192.168.219.160:8080/coffee247soft/";
	
	private String url;
	private ByteArrayOutputStream baos;
	private ParserHandler parser;
	private List<?> list;
	
	public Request247soft(String url, ByteArrayOutputStream baos, ParserHandler parser)
	{
		this.url = url;
		this.baos = baos;
		this.parser = parser;
	}
	
	public List<?> connection() throws Exception
	{
		String name = preUrl + url;
		InputStream in = null;
		URL connectURL = new URL(name);
		HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
		
		conn.setConnectTimeout(5000);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false); 			
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/octet-stream");
		
		DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
		byte [] data = baos.toByteArray();
		dos.writeInt(data.length);
		dos.write(data);
		dos.flush();
		
		int responseCode = conn.getResponseCode();
		if (responseCode == HttpsURLConnection.HTTP_OK)
		{
			in = conn.getInputStream();
		}
		else
		{
			throw new Exception();
		}
		
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser saxParser = factory.newSAXParser();
		
		saxParser.parse(in, parser);
		
		list = parser.getList();
		
		return list;
	}
}
